import Widget from './Widget'
import { WidgetType } from '@/types'
import { getDocPageSum } from '@/components/contract/utils'
import { moveCheckGroupWidget } from '@/widgets/checkbox-group/utils'
import { getLinkPageRange } from './link'

/** 获取控件最小页面范围 */
export function getPageRange(widget: Widget) {
  const { isRiding, isBatch, page } = widget

  if (!isRiding && !isBatch) {
    return {
      minWidth: page.w,
      minHeight: page.h
    }
  }

  const { minWidth, minHeight } = isBatch ? getLinkPageRange(widget) : getDocPageSum(widget.doc)

  return { minWidth, minHeight }
}

/** 获取控件定位范围 */
export function getRange(widget: Widget) {
  const { w, h, page, isRiding, isBatch } = widget
  let { w: pw = Infinity, h: ph = Infinity } = page || {}

  if (isRiding || isBatch) {
    const { minWidth, minHeight } = widget.pageRange
    pw = minWidth
    ph = minHeight
  }

  return {
    minX: 0,
    minY: 0,
    maxX: isRiding ? 0 : Math.max(pw - w, 0),
    maxY: Math.max(ph - h, 0)
  }
}

/** 移动控件 */
export async function moveWidget(widget: Widget, x = 0, y = 0, adjust = true) {
  await widget.initPromise

  // 单复选框需要同步移动子选项
  if ([WidgetType.RADIO_GROUP, WidgetType.CHECKBOX_GROUP].includes(widget.type)) {
    moveCheckGroupWidget(widget, x, y)
  } else {
    x && (widget.x += x)
    y && (widget.y += y)
  }

  adjust && widget.adjust()
}

/** 适应控件位置以免超出边界 */
export function adjustLocation(widget: Widget) {
  const { minX, minY, maxX, maxY } = widget.range
  let { x, y } = widget

  if (x > maxX) {
    x = maxX
  } else if (x < minX) {
    x = minX
  }

  if (y > maxY) {
    y = maxY
  } else if (y < minY) {
    y = minY
  }

  Object.assign(widget, { x, y })
}

/**
 * 获取拖拽结束后控件位置，跨页后修复坐标和页码
 */
export function getDropLocation(widget: Widget) {
  let { viewer } = widget
  let { x, y, oy, w, h, p, page } = widget

  if (!viewer || !page) return { p, x, y, w, h }

  const {
    state: { pages, pageCount },
    zoom: { level: zoomLevel },
    pageSpacing
  } = viewer

  const spacing = pageSpacing / zoomLevel

  const maxP = pageCount - 1

  const lastPage = page

  if (oy < 0) {
    // 拖动到前页
    while (oy < 0) {
      p--

      // 第一页
      if (p < 0) {
        p = 0
        y = 0
        oy = y + h / 2
      } else {
        page = pages[p]

        y += page.h + spacing

        if (y > page.h - h) {
          y = page.h - h
        }

        oy = y + h / 2
      }
    }
  } else if (oy > page.h) {
    // 拖动到后页
    while (oy > page.h) {
      p++

      // 尾页
      if (p > maxP) {
        p = maxP
        y = pages[maxP].h - h
        oy = y + h / 2
        break
      } else {
        y -= page.h + spacing

        if (y < 0) y = 0

        oy = y + h / 2

        page = pages[p]
      }
    }
  }

  // 异形合同跨页后宽度改变则更改 x 坐标
  if (lastPage.w !== page.w) {
    x += (page.w - lastPage.w) / 2
  }

  return { p, x, y, w, h }
}
